<?php

/*
*
* BEGIN ajaxcontroller.php
*
*
* Dazzler Ajax Controller
* @Description: handles and services all ajax calls
* @Authors: Salman Noor, Wits University
* @Copyright: © Wits University 2011 - All Rights Reserved
* @License: BSD License (http://www.linfo.org/bsdlicense.html)
*
*
* BEGIN CHANGELOG
* Developers working on thee files are REQUIRED to maintain this CHANGELOG.
* Please ensure you follow the Changelog Guidelines: http://code.google.com/p/dazzler/wiki/DazzlerDevelopGuideline?ts=1315476570&updated=DazzlerDevelopGuideline
* !==================================================================================================================================================================
*
* VERSION 1.0.0
*	+ Created, Salman, 14 September 2011
*
* ==================================================================================================================================================================!
* END CHANGELOG
*/


/*******************************************************************************************************************************************************************
*
* BEGIN Direct Call Check
*
/******************************************************************************************************************************************************************/
global $doNotCallThisScriptDirectly;
if ($doNotCallThisScriptDirectly != 1)
{
	/* Read the ini language file */
	$ini_lang_array = array();
	$clientlang = explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
	$lang_ini_array = (file_exists("lang/" . trim($clientlang[0]) . ".ini")) ? parse_ini_file("lang/" . trim($clientlang[0]) . ".ini", true) : parse_ini_file("lang/en.ini", true);
	die ($lang_ini_array['ERRORS']['doNotCallThisScriptDirectly']);
}
/*******************************************************************************************************************************************************************
*
* END Direct Call Check
*
/******************************************************************************************************************************************************************/

/*******************************************************************************************************************************************************************
* BEGIN loader class declaration
/******************************************************************************************************************************************************************/
class ajaxcontroller {

    private $ajaxTracerIsEnabled;
    public function __construct() {

        $parsesiteconfig = new parsesiteconfig();
        if ($parsesiteconfig->checkIfAjaxTracerIsEnabled())
        {
            $this->ajaxTracerIsEnabled = true;
        }
        else
        {
            $this->ajaxTracerIsEnabled = false;
        }
    }

    public function dispatch($action) {

///Get action from query string and set default to home
///Convert the action into a method
        $method = $this->__getMethod($action);
///Return the template determined by the method resulting from action
        return $this->$method();
    }

    /* !
     * \brief checks if the action exists
     *  \return A boolean value
     * \param action a string containing the action
     */

    private function __validAction(& $action) {
///Checks if the methods exists and returns a simple boolean value
        if (method_exists($this, "__" . $action)) {
/// Method exists in a member function of the controller class from the chisimba core
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /* !
     * \brief Get an action
     * \param action A string
     *  \return the method that corresponds to the action
     */

    private function __getMethod(& $action) {
///Checks using __validAction if the action exists and returns the corresponding method
        if ($this->__validAction($action)) {
            return "__" . $action;
        } else {
///If methos does not exist return the method __actionError which returns
///a template displaying an error
            return "__actionError";
        }
    }

     /* !
     * \brief This method logs a trace into a text file in this folder
     * \param msg Message to be logged into the trace file
     *  \return Nothing
     */
     private function logToFile($msg) {
// open file
        $fd = fopen("ajaxtracer.txt", "a");
// write string
        fwrite($fd, $msg . "\n");
// close file
        fclose($fd);
    }

    private function __loginUser() {

        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        $autenticationSuccess = null;
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Login User Action:");
            $this->logToFile("Parameters - Login Type:" . $parameters['loginType']);
            $this->logToFile("Parameters - Login Name:" . $parameters['loginName']);
        }
        $UserLogic = new UserLogic();
 //echo $UserLogic->logOn($parameters['loginName'], $parameters['loginPassword']);
            if ($UserLogic->logOn($parameters['loginName'], $parameters['loginPassword']) != "1") {
                echo "Error. User does not exist.";
                $autenticationSuccess = false;
            }
            else
            {
                $autenticationSuccess = true;
            }

        if ($autenticationSuccess) {
            echo "1";
        }
    }

    private function __getCommentatorContent()
    {
     $side_nav_content = new side_nav_content();
     $commentatorSideNav = $side_nav_content->showCommentatorSideNav();
     $contentArray = array('side_nav' => $commentatorSideNav);
     echo json_encode($contentArray);
    }

        private function __getCricketFanContent()
    {
     $side_nav_content = new side_nav_content();
     $commentatorSideNav = $side_nav_content->showCricketFanSideNav();
     $contentArray = array('side_nav' => $commentatorSideNav);
     echo json_encode($contentArray);
    }
    private function __getCommentatorJSFiles()
    {
        $parsesiteconfig = new parsesiteconfig();
        $path = $parsesiteconfig->getDocumentPath();
        $rootpath = $parsesiteconfig->getRootPath();
        $loadType = $parsesiteconfig->getLoadType();
        $cm = new fetchpathitems($path . "/sites/dazzler/themes/$loadType/custom/scripts/commentator", "js");
        $js_head = null;
	foreach($cm->cm as $includeJsFile)
	{
		$js_head .= "<script src='$rootpath/themes/$loadType/custom/scripts/commentator/$includeJsFile'></script>\n";
	}
        echo $js_head;
    }

    private function __insertNewTeam()
    {
           $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Insert New Team - Action:");
            $this->logToFile("Parameters - Team Name :" . $parameters['teamName']);
            $this->logToFile("Parameters - Team short Name :" . $parameters['shortName']);
        }
              $insertSuccess = null;
              $gameAdmin = new GameAdmin();
              $insertSuccess =  $gameAdmin->insertTeam($parameters['teamName'], $parameters['shortName']);
              if ($insertSuccess == FALSE)
              {
                 echo "Error. Insert Team into Dazzler has failed.";

              }
              else
              {
                 echo $insertSuccess;
              }
    }

    private function __getAddTeamForm()
    {
     $team_management_ui = new team_management_ui();
     echo $team_management_ui->showAddTeamForm();
    }

    private function __getAddPlayerForm()
    {
     $player_management_ui = new player_management_ui();
     echo $player_management_ui->showAddPlayerForm();
     //echo $team_management_ui->showAddTeamForm();
    }

    private function __insertNewPlayer()
    {
          $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
          //$parameters);
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Insert New Player - Action:");
            $this->logToFile("Parameters - First Name :" . $parameters['firstName']);
           $this->logToFile("Parameters - Last Name :" . $parameters['lastName']);
                 $this->logToFile("Parameters - Team ID :" . $parameters['teamNameID']);
            $this->logToFile("Parameters - Date of Birth :" . $parameters['dob']);
                        $this->logToFile("Parameters - Place of Birth :" . $parameters['pob']);
                $this->logToFile("Parameters - Nick Name :" . $parameters['nickName']);
                $this->logToFile("Parameters - Height :" . $parameters['height']);
               $this->logToFile("Parameters - Player Profile :" . $parameters['playerProfile']);
               $this->logToFile("Parameters - Fielding Position :" . $parameters['fieldingPosition']);
               $this->logToFile("Parameters - Batsman Type :" . $parameters['batsmanType']);
               $this->logToFile("Parameters - Bowling Type :" . $parameters['bowlingType']);
               $this->logToFile("Parameters - Is Specialist Batsman :" . $parameters['isSpecialistBatsman']);

        }
        $PlayerAdmin = new PlayerAdmin();
if ($parameters['isSpecialistBatsman'] =='true')
{
 $isSpecialistBatsman = TRUE;
}
else
{

 $isSpecialistBatsman = FALSE;
}
        $insertionSuccess = $PlayerAdmin->insertPlayer($parameters['firstName'], $parameters['lastName'], $parameters['teamNameID'], $parameters['dob'], $parameters['pob'],$parameters['nickName'],$parameters['height'], $parameters['playerProfile'], $parameters['fieldingPosition'], $parameters['bowlingType'], $parameters['batsmanType'],$isSpecialistBatsman);
    if($insertionSuccess == FALSE)
    {
      echo "Error. Insert Player into Dazzler has failed.";
    }
    else
    {
          echo $insertionSuccess;
    }

    }

    private function __getAddGameForm()
    {
        $game_management_ui = new game_management_ui();
        echo $game_management_ui->showAddGameForm();
    }

    private function __viewPlayerDetails()
    {
          $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
          
          $player_management_ui = new player_management_ui();
          echo $player_management_ui->showPlayerDetails($parameters['playerID']);
    }

    private function __updateTeamList()
    {
        $team_management_ui = new team_management_ui();
        echo $team_management_ui->showListAllTeams();
    }

    private function __updatePlayerList()
    {
        $player_management_ui = new player_management_ui();
        echo $player_management_ui->showPlayerList();
    }

    private function __getTeamRanksManager()
    {
      $team_management_ui = new team_management_ui();
     echo $team_management_ui->showTeamRankingList();
    }

    private function __getDeleteTeamForm()
    {
        $team_management_ui = new team_management_ui();
        echo $team_management_ui->showDeleteTeams();
    }

    private function __deleteTeam()
    {
       $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
         if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Delete Team - Action:");
            $this->logToFile("Parameters - Team Name :" . $parameters['teamName']);
           $this->logToFile("Parameters - Team ID :" . $parameters['teamID']);
        }

        $GameAdmin = new GameAdmin();
        $deleteSuccess = $GameAdmin->deleteTeamByID($parameters['teamID']);
        if ($deleteSuccess)
        {
            echo 1;
        }
        else
        {
            echo "Error. Delete Failed. Contact your software administrator.";
        }
    }

    private function __deletePlayer()
    {
       $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
         if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Delete Player - Action:");
            $this->logToFile("Parameters - Team Name :" . $parameters['playerName']);
           $this->logToFile("Parameters - Team ID :" . $parameters['playerID']);
        }
        $PlayerAdmin = new PlayerAdmin();
        $deleteSuccess = $PlayerAdmin->deletePlayer($parameters['playerID']);
        if ($deleteSuccess)
        {
            echo 1;
        }
        else
        {
            echo "Error. Delete Failed. Contact your software administrator.";
        }
    }

    private function __getMatchTossForm()
    {
            $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;

         if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Get Match Toss Form - Action:");
            $this->logToFile("Parameters - Home Team Name :" . $parameters['homeTeamName']);
           $this->logToFile("Parameters - Away Team Name :" . $parameters['awayTeamName']);
          $this->logToFile("Parameters - Home Team ID :" . $parameters['homeTeamID']);
            $this->logToFile("Parameters - Away Team ID :" . $parameters['awayTeamID']);
        }
        $game_management_ui = new game_management_ui();
        echo $game_management_ui->showGameTossForm($parameters['homeTeamID'], $parameters['homeTeamName'], $parameters['awayTeamID'], $parameters['awayTeamName']);
    }

    private function __registerNewMatch()
    {
        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("REgister New Match - Action:");
            $this->logToFile("Parameters - Match Name :" . $parameters['matchName']);
           $this->logToFile("Parameters - Match Type :" . $parameters['matchType']);
          $this->logToFile("Parameters - Match Venue :" . $parameters['matchVenue']);
            $this->logToFile("Parameters - First Empire :" . $parameters['firstEmpire']);
        $this->logToFile("Parameters - Second Empire :" . $parameters['secondEmpire']);
        $this->logToFile("Parameters - Third Empire :" . $parameters['thirdEmpire']);
        $this->logToFile("Parameters - Reserve Empire :" . $parameters['reserveEmpire']);
        $this->logToFile("Parameters - Match Referee :" . $parameters['matchReferee']);
        $this->logToFile("Parameters - Home Team ID :" . $parameters['homeTeamID']);
        $this->logToFile("Parameters - Away Team ID :" . $parameters['awayTeamID']);
        $this->logToFile("Parameters - Home Team Name :" . $parameters['homeTeamName']);
        $this->logToFile("Parameters - Away Team Name :" . $parameters['awayTeamName']);
        $this->logToFile("Parameters - Bat First Team ID :" . $parameters['batFirstTeamID']);
        $this->logToFile("Parameters - Bat First Team Name :" . $parameters['batFirstTeamName']);
        $this->logToFile("Parameters - Toss Commentary :" . $parameters['tossCommentary']);
        }
        $GameAdmin = new GameAdmin();
        $insertSuccess = $GameAdmin->registerGame($parameters['matchName'], $parameters['homeTeamName'], $parameters['awayTeamName'], $parameters['batFirstTeamName'], $parameters['matchType'], $parameters['matchVenue'], $parameters['tossCommentary'], $parameters['firstEmpire'], $parameters['secondEmpire'],$parameters['thirdEmpire'],$parameters['reserveEmpire'],$parameters['reserveEmpire']);

        if (is_numeric($insertSuccess))
         {
            echo $gameID = $insertSuccess;
             $GameAdmin->activateGame($gameID);
         }
         else
         {
             echo "Error. Match registration has failed. Match Title already exists. Please insert another match title.";
         }
        //print_r($parameters);
    }

    private function __getInsertPlayerIntoGameForm()
    {
           $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;

        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Get Insert Player Into Game Form - Action:");
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);

        }
         if (is_numeric($parameters['gameID']))
         {
        
             $game_management_ui = new game_management_ui();
             echo $game_management_ui->showInsertPlayerIntoForm($parameters['gameID']);
         }
         else
         {
             echo "Error. You have entered this page illegally. Game ID has not been set.";
         }
    }

    private function __getDeletePlayerForm()
    {
        $player_management_ui = new player_management_ui();
        echo $player_management_ui->showDeletePLayerList();
    }

    private function __updateTeamRankings()
    {
    $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
    $unrankedTeamsArray = json_decode($parameters['unrankedTeams'],true);
    $rankedTeamsArray = json_decode($parameters['rankedTeams'],true);
    $GameAdmin = new GameAdmin();
    foreach ($unrankedTeamsArray as $key => $teamName) {
  $GameAdmin->updateTeamRankByName($teamName, "0");
    }

        foreach ($rankedTeamsArray as $key => $teamName) {
            $rank = $key+1;
            $GameAdmin->updateTeamRankByName($teamName, $rank);
    }
   
echo 1;
       

    }



    private function __getBallByBallCommentaryForm()
    {
        //echo "yes";

    $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
                if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Get Insert Ball By Ball Commentary Form - Action:");
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);


        }
        $GameAdmin = new GameAdmin();
        $GameAdmin->activateGame($parameters['gameID']);
        $commentary_management_ui = new commentary_management_ui($parameters['gameID']);
        echo $commentary_management_ui->showInsertBallCommentaryForm();
    }

    private function __getBallStatsIndicator()
    {

        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
                if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Get Insert Ball By Ball Commentary Form - Action:");
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);


        }

        $commentary_management_ui = new commentary_management_ui($parameters['gameID']);
        echo $commentary_management_ui->showBallStatsIndicator();
    }

    private function __getFinalResultCommentaryForm()
    {
        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Get Insert Ball By Ball Commentary Form - Action:");
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);


        }

        $commentary_management_ui = new commentary_management_ui($parameters['gameID']);
        echo $commentary_management_ui->showFinalResultCommentaryForm();
    }

    private function __deactivateGame()
    {
              $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Deactivate Game - Action:");
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);
        }

        $GameAdmin = new GameAdmin();
        $GameAdmin->deactivateGame($parameters['gameID']);
    }

    private function __finalizeGame()
    {
        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Inset Final Result - Action:");
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);
            $this->logToFile("Parameters - Final Result Commentary :" . $parameters['finalResultCommentary']);

        }

        $StatsAdmin = new StatsAdmin();
        $updateSuccess = $StatsAdmin->finaliseGameResult($parameters['gameID'], $parameters['finalResultCommentary']);
        if ($updateSuccess)
        {
            echo "1";
        }
        else
        {
            echo "0";
        }
   
    }

    private function __insertBallCommentary()
    {
         $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
                         if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Insert Ball Commentary - Action:");

            $this->logToFile("Parameters - bowlType :" . $parameters['commentatorID']);
            $this->logToFile("Parameters - bowlType :" . $parameters['bowlType']);
            $this->logToFile("Parameters - Bat Shot Type :" . $parameters['batShotType']);
            $this->logToFile("Parameters - Runs Made :" . $parameters['runs']);
            $this->logToFile("Parameters - Ball Commentary :" . $parameters['commentary']);
            $this->logToFile("Parameters - Batsman Facing ID :" . $parameters['batsmanID']);
            $this->logToFile("Parameters - Bowler Bowling ID :" . $parameters['bowlerID']);
            $this->logToFile("Parameters - Game ID :" . $parameters['gameID']);
            $this->logToFile("Parameters - is Dismissal Bool :" . $parameters['isDismissal']);
            $this->logToFile("Parameters - Dismissal Type :" . $parameters['dismissalType']);
            $this->logToFile("Parameters - is Extra Bool :" . $parameters['isExtra']);
            $this->logToFile("Parameters - Extra Type :" . $parameters['extraType']);
            $this->logToFile("Parameters - Ball Trajectory Type :" . $parameters['trajectoryType']);
            $this->logToFile("Parameters - Ball Trajectory Parameters :" . $parameters['ballTrajectoryParameters']);
        }

        if ($parameters['isDismissal'] == "1")
        {
            $isDissmisal = TRUE;
        }
        else
        {
            $isDissmisal = FALSE;
        }

        if ($parameters['isExtra'] == "1")
        {
            $isExtra = TRUE;
        }
        else
        {
            $isExtra = FALSE;
        }

        $bowlType = str_replace('&nbsp;', "", $parameters['bowlType']);
        $batShotType = str_replace("&nbsp;", "", $parameters['batShotType']);
        $StatsAdmin = new StatsAdmin();
        //$StatsAdmin->deleteBallByBall($parameters['gameID']);
        
        $insertionSuccess = $StatsAdmin->insertBallByBall($parameters['commentatorID'],$bowlType, $batShotType, $parameters['runs'], $parameters['commentary'], $parameters['batsmanID'], $parameters['bowlerID'], $parameters['gameID'], $isDissmisal, $parameters['dismissalType'],$isExtra,$parameters['extraType']);
     // print_r($insertionSuccess);
        if ($insertionSuccess['success'] == "1")
        {
            $BallTrajectoryDataHandler = new BallTrajectoryDataHandler();
            $BallTrajectoryDataHandler->insertBallTrajectory($insertionSuccess['ballID'], $parameters['trajectoryType'], $parameters['ballTrajectoryParameters']);

                if(!$StatsAdmin->isGameFinished( $parameters['gameID']))
               {
                   echo "1";
                  // echo $insertionSuccess['ballID'];
               }
               else
               {
                   echo "2";
                   // echo $insertionSuccess['ballID'];
               }
               //echo "yes";
        }
        else
        {
              echo $insertionSuccess['success'];
        }
    
    }

    private function __registerPlayersToMatch()
    {
     $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
    $homeTeamPlayerArray = $parameters['homeTeam'];
    $awayTeamPlayerArray = $parameters['awayTeam'];
    //print_r($parameters['awayTeam']);
   // print_r($parameters['awayTeam']);
    $GameID = $parameters['gameID'];

    $PlayerAdmin = new PlayerAdmin();
    $PlayerAdmin->deletePlayersFromGame($GameID);
//    foreach ($array as $key => $value) {
//
//    }
    foreach ($homeTeamPlayerArray as $homePlayer) {

         $insertionSuccess = $PlayerAdmin->registerPlayer4Game($GameID, $homePlayer['playerPoolID'], $homePlayer['batOrder'], $homePlayer['isBowler'], $homePlayer['isCaptain']);
      if (!$insertionSuccess)
      {
          echo $insertionSuccess;
          return 0;
      }
      }
      
      foreach ($awayTeamPlayerArray as $awayPlayer) {

         $insertionSuccess = $PlayerAdmin->registerPlayer4Game($GameID, $awayPlayer['playerPoolID'], $awayPlayer['batOrder'], $awayPlayer['isBowler'], $awayPlayer['isCaptain']);
      if (!$insertionSuccess)
      {
          echo $insertionSuccess;
          return 0;
      }
      }
      
      $GameAdmin = new GameAdmin();
      $GameAdmin->finaliseGamePlayers($GameID);

        echo  1;
   
    //$PlayerAdmin->registerPlayer4Game($teamId, $gameId, $playerPoolId, $batOrder, $isPlayerBowler, $isCaptain)
    }


        public function __addNewUser() {
        //echo "yes";
        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
        //$dbtable = new database_tables_handler();
        if ($this->ajaxTracerIsEnabled)
        {
            $this->logToFile("Add New User - Action:");
            $this->logToFile("Parameters - first Name :" . $parameters['firstName']);
            $this->logToFile("Parameters - last Name :" . $parameters['lastName']);
            $this->logToFile("Parameters - user Name :" . $parameters['userName']);
            $this->logToFile("Parameters - Extra User Info :" . $parameters['extraUserInfo']);
            $this->logToFile("Parameters - form Email :" . $parameters['formEmail']);
        }
        $registrationSuccess = null;
       // $userData = array(null, $parameters['firstName'], $parameters['lastName'], $parameters['userName'], $parameters['formPassword'], $parameters['formEmail']);
        $userAdmin = new UserAdmin();
        if ($parameters['userType'] == 'commentator') {

            if ($userAdmin->isUsernameAvailable($parameters['userName'])) {
                $insertion_id = $userAdmin->registerCommntor($parameters['firstName'], $parameters['lastName'], $parameters['userName'], $parameters['formPassword'], $parameters['extraUserInfo'], $parameters['formEmail']);
            } else {
                echo "Error. Username already exists.";
                return false;
            }
        } else {

            if ($userAdmin->isUsernameAvailable($parameters['userName']))  {
                $insertion_id = $userAdmin->registerFan($parameters['firstName'], $parameters['lastName'], $parameters['userName'], $parameters['formPassword'], $parameters['extraUserInfo'], $parameters['formEmail']);
            } else {
                echo "Error. Username already exists.";
                return false;
            }
        }

        $phpmailer = new phpmailer(true);
        $phpmailer->IsSMTP();
        // $phpmailer->AddEmbeddedImage('wits-crest.gif', 'logoimg', 'wits-crest.gif','base64','image/gif'); // attach file logo.jpg, and later link to it using identfier logoimg
        $body = "<h1>Dazzler</h1>
            <p>Dear ". $parameters['firstName'] ." ".$parameters['lastName'] .",</p>
            <p> Thank you for registering with Dazzler as a ". $parameters['userType'] .". Your registration details are as follows:</p>
           <ul>
                <li> First Name : ". $parameters['firstName']."</li>
                <li> Last Name : ". $parameters['lastName']."</li>
                <li> Login User Name : ". $parameters['userName']."</li>
                <li> Login Password : ". $parameters['formPassword']."</li>
           </ul>
           <p>Thank You.</p>
           <p>The Dazzler Development Team</p>";
        $phpmailer->AddReplyTo('noreply@dazzler.com', 'Dazzler');
        $phpmailer->AddAddress($parameters['formEmail']);
        $phpmailer->Subject = "Dazzler User Registration Successful";
        $phpmailer->SetFrom('noreply@dazzler.com', 'Dazzler');
        $phpmailer->AltBody = $body;
        $phpmailer->MsgHTML($body);
        if ($phpmailer->Send())
        {
                $registrationSuccess=1;
        }
        else
        {
            echo "Error. PHP Mailer has failed to send a mail to your email address";
            $registrationSuccess = 3;
            return false;
        }


        echo $registrationSuccess;
    }

    



  

}

?>
